package com.blog.utils;

import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;

import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Component
public class IndexMappingCreator {
    @Resource
    private RestHighLevelClient restHighLevelClient;
    public void createBlogIndex() throws Exception {
        // 是否存在索引
        GetIndexRequest exitrequest = new GetIndexRequest("blog");
        boolean exists = restHighLevelClient.indices().exists(exitrequest, RequestOptions.DEFAULT);

        if(!exists) {
            CreateIndexRequest request = new CreateIndexRequest("blog");
            ClassPathResource resource = new ClassPathResource("/elasticsearch/settings.json");
            String settingsJson = FileCopyUtils.copyToString(
                    new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)
            );

            request.settings(Settings.builder().loadFromSource(settingsJson, XContentType.JSON));
            // 3. 手动定义映射，指定suggest为completion类型
            XContentBuilder mapping = JsonXContent.contentBuilder()
                    .startObject()
                    .startObject("properties")
                    // title字段映射
                    .startObject("title")
                    .field("type", "text")
                    .field("analyzer", "ik_max_word")
                    .startObject("fields")
                    .startObject("pinyin")
                    .field("type", "text")
                    .field("analyzer", "ik_pinyin_analyzer")
                    .endObject()
                    .startObject("keyword")
                    .field("type", "keyword")
                    .endObject()
                    .endObject()
                    .endObject()
                    // content字段映射
                    .startObject("content")
                    .field("type", "text")
                    .field("analyzer", "ik_max_word")
                    .startObject("fields")
                    .startObject("pinyin")
                    .field("type", "text")
                    .field("analyzer", "ik_pinyin_analyzer")
                    .endObject()
                    .endObject()
                    .endObject()
                    // suggest字段映射（关键：completion类型）
                    .startObject("suggest")
                    .field("type", "completion")
                    .field("preserve_separators", false)
                    .field("preserve_position_increments", false)
//                    .field("analyzer", "ik_pinyin_analyzer")
//                    .field("search_analyzer", "ik_pinyin_analyzer")

                    .endObject()
                    // 其他字段映射
                    .startObject("createTime").field("type", "date").field("format", "yyyy-MM-dd HH:mm:ss").endObject()
                    .startObject("updateTime").field("type", "date").field("format", "yyyy-MM-dd HH:mm:ss").endObject()
                    .startObject("viewCount").field("type", "integer").endObject()
                    .startObject("categoryId").field("type", "integer").endObject()
                    .startObject("status").field("type", "integer").endObject()
                    .startObject("author").field("type", "text").endObject()
                    .startObject("authorId").field("type", "integer").endObject()
                    .endObject()
                    .endObject();
            request.mapping(mapping);
            AcknowledgedResponse response = restHighLevelClient.indices()
                    .create(request, RequestOptions.DEFAULT);

            if (response.isAcknowledged()) {
                System.out.println("索引创建成功，已手动添加completion类型映射");
            } else {
                System.out.println("索引创建失败");
            }
        }
    }
}
